
package com.gamatechno.solodestinationnew;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.facebook.HttpMethod;
import com.facebook.LoggingBehavior;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.Settings;
import com.gamatechno.solodestinationnew.entity.E_Komentar;
import com.gamatechno.solodestinationnew.helper.JSONHelper;
import com.gamatechno.solodestinationnew.utils.CircleTransform;
import com.gamatechno.solodestinationnew.utils.Utils;
import com.gamatechno.solodestinationnew.utils.Webservice;
import com.google.android.gms.maps.model.LatLng;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.squareup.picasso.Picasso;

public class DetailLocationActivity extends BaseActivity implements OnClickListener {
    private TextView title, distance;
    private WebView description;
    private ImageView img;
    private RatingBar rating;
    private ImageView btnMap;

    private Bundle data;
    private int category;
    private ProgressBar pBar;
    private int locationID;
    private LatLng loc;
    private LinearLayout containerKomentar;
    private List<E_Komentar> listKomentar;
    private LayoutInflater inflater;
    private Button btnKomentar;
    private Session.StatusCallback statusCallback = new SessionStatusCallback();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail_location);

        overridePendingTransition(R.anim.activity_open_translate, R.anim.activity_close_scale);

        getSupportActionBar().setDisplayHomeAsUpEnabled(false);

        inflater = LayoutInflater.from(this);

        Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
        Session session = Session.getActiveSession();

        if (session == null) {

            if (savedInstanceState != null)
                session = Session.restoreSession(this, null, statusCallback, savedInstanceState);
            if (session == null)
                session = new Session(this);

            Session.setActiveSession(session);
            if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
                session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
            }
        }
        // updateState();

        data = getIntent().getExtras();
        if (data != null) {
            category = data.getInt("cat");
            locationID = Integer.parseInt(data.getString("id"));
        }

        listKomentar = new ArrayList<E_Komentar>();

        title = (TextView) findViewById(R.id.title);
        rating = (RatingBar) findViewById(R.id.rating);
        img = (ImageView) findViewById(R.id.img_banner_detail_location);
        pBar = (ProgressBar) findViewById(R.id.loader);
        distance = (TextView) findViewById(R.id.txt_distance);
        description = (WebView) findViewById(R.id.wv_description);
        btnMap = (ImageView) findViewById(R.id.btn_map);
        btnKomentar = (Button) findViewById(R.id.btn_komentar);
        containerKomentar = (LinearLayout) findViewById(R.id.container_komentar);

        pBar.setVisibility(View.VISIBLE);

        rating.setRating(data.getFloat("rating"));
        title.setText(data.getString("title"));
        if (data != null) {
            distance.setText(String.format("%.2f", data.getDouble("distance")) + " km");
        }

        description.loadData(data.getString("desc"), "text/html", "utf-8");

        loc = new LatLng(data.getDouble("lat"), data.getDouble("lng"));

        ImageLoader.getInstance().displayImage(data.getString("img"), img,
                BaseApplication.getDisplayImageOptions(),
                new SimpleImageLoadingListener() {
                    @Override
                    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                        super.onLoadingComplete(imageUri, view, loadedImage);
                        if (pBar != null)
                            pBar.setVisibility(View.GONE);
                    }
                });

        btnMap.setOnClickListener(this);
        btnKomentar.setOnClickListener(this);

    }

    @Override
    protected void onResume() {
        super.onResume();
        Utils.TRACE("DetailLocationActivity", "onResume : ");
        if (data != null) {
            switch (category) {
                case MainActivity.CATEGORY_HOTEL:
                    getKomentar(Webservice
                            .GET_COMMENT_HOTEL(Integer.parseInt(data.getString("id"))));
                    break;
                case MainActivity.CATEGORY_KULINER:
                    getKomentar(Webservice.GET_COMMENT_KULINER(Integer.parseInt(data
                            .getString("id"))));
                    break;
                case MainActivity.CATEGORY_TOURISM:
                    getKomentar(Webservice
                            .GET_COMMENT_WISATA(Integer.parseInt(data.getString("id"))));
                    break;
                case MainActivity.CATEGORY_HANDYCRAFT:
                    getKomentar(Webservice
                            .GET_COMMENT_HANDYCRAFT(Integer.parseInt(data.getString("id"))));
                    break;
                case MainActivity.CATEGORY_SHOPPING:
                    getKomentar(Webservice.GET_COMMENT_SHOPPING(Integer.parseInt(data
                            .getString("id"))));
                    break;

            }
        }
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        overridePendingTransition(R.anim.activity_open_scale, R.anim.activity_close_translate);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public void onClick(View v) {
        if (v == btnMap) {
            Intent i = new Intent(android.content.Intent.ACTION_VIEW, Uri
                    .parse("http://maps.google.com/maps?daddr=" + loc.latitude + ","
                            + loc.longitude));
            startActivity(i);
        } else if (v == btnKomentar) {

            if (Utils.getDataBooleanFromSP(this, Utils.PREF_ISLOGIN)) {
                Bundle d = new Bundle();
                d.putString("title", data.getString("title"));
                d.putInt("id", locationID);
                d.putInt("cat", category);
                startActivity(new Intent(this, RateActivity.class).putExtras(d));
            } else {
                Toast.makeText(this, "Need Login", Toast.LENGTH_SHORT).show();
                loginFB();
            }
        }
    }

    private void getKomentar(String URL) {
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,
                URL,
                null,
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject obj) {
                        Utils.TRACE("DetailLocationActivity.getKomentar(...).new Listener() {...}",
                                "onResponse : " + obj.toString());
                        try {
                            if (obj.getInt("status") == 200) {
                                if (obj.getJSONArray("result").length() > 0) {
                                    if (listKomentar.size() > 0) {
                                        Utils.TRACE(
                                                "DetailLocationActivity",
                                                "onResponse : clear komentar");
                                        listKomentar.clear();
                                    }
                                    listKomentar = JSONHelper.getListKomentar(obj
                                            .getJSONArray("result"));
                                    generateKomentar(listKomentar);
                                }
                            }
                        } catch (JSONException e) {
                            Utils.TRACE(
                                    "DetailLocationActivity.getKomentar(...).new Listener() {...}",
                                    "onResponse : " + e.getMessage());
                        }
                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Utils.TRACE(
                                "DetailLocationActivity.getKomentar(...).new ErrorListener() {...}",
                                "getKomentar : " + error.toString());
                        Utils.showVolleyError(DetailLocationActivity.this, error);
                    }
                });
        BaseApplication.getInstance().addToRequestQueue(request, "detail");

    }

    protected void generateKomentar(List<E_Komentar> listKomentar) {

        if (containerKomentar.getChildCount() > 0)
            containerKomentar.removeAllViews();

        for (E_Komentar komentar : listKomentar) {

            View view = inflater.inflate(R.layout.item_comment_location, null);
            // view.setBackgroundColor(Color.parseColor("#80000000"));

            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);

            params.setMargins(0, 0, 0, 20);
            view.setLayoutParams(params);
            final ImageView imgThumb = (ImageView)
                    view.findViewById(R.id.thumb_user_comment);
            final TextView txtUsername = (TextView) view.findViewById(R.id.comment_username);
            final TextView txtDate = (TextView) view.findViewById(R.id.comment_date);
            final RatingBar rate = (RatingBar) view.findViewById(R.id.comment_rate);
            final TextView txtComment = (TextView) view.findViewById(R.id.comment_text);

            txtUsername.setText(komentar.getName());
            txtDate.setText(komentar.getDate());
            rate.setRating(komentar.getRating());
            txtComment.setText(komentar.getKomentar());

            getImageUserFB(Webservice.GET_FB_PHOTO(komentar.getIduser()), imgThumb);

            containerKomentar.addView(view);
        }
    }

    private void getImageUserFB(String URL, final ImageView img) {
        Utils.TRACE("DetailLocationActivity", "getImageUserFB : ");
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,
                URL,
                null,
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject obj) {
                        try {
                            JSONObject objectData = obj.getJSONObject("data");

                            Picasso.with(DetailLocationActivity.this)
                                    .load(objectData.getString("url"))
                                    .transform(new
                                            CircleTransform()).into(img);
                        } catch (JSONException e) {
                            Utils.TRACE(
                                    "DetailLocationActivity.getImageUserFB(...).new Listener() {...}",
                                    "onResponse : " + e.getMessage());
                        }
                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Utils.TRACE(
                                "DetailLocationActivity.getImageUserFB(...).new ErrorListener() {...}",
                                "getImageUserFB : " + error.getMessage());
                    }
                });
        BaseApplication.getInstance().addToRequestQueue(request, "img");
    }

    private class SessionStatusCallback implements Session.StatusCallback {
        @Override
        public void call(Session session, SessionState state, Exception exception) {
            updateState();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        Session.getActiveSession().addCallback(statusCallback);
    }

    @Override
    protected void onStop() {
        super.onStop();
        Session.getActiveSession().removeCallback(statusCallback);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
    }

    public void updateState() {
        Session session = Session.getActiveSession();
        if (session.isOpened()) {
            Utils.TRACE("MainActivity", "updateState : User Logged");
            Utils.setDataBooleanToSP(this, Utils.PREF_ISLOGIN, true);

            getUserData(session);
            // Toast.makeText(this, "Login succesfull",
            // Toast.LENGTH_SHORT).show();
        }
    }

    private void loginFB() {
        Session session = Session.getActiveSession();
        if (!session.isOpened() && !session.isClosed()) {
            Utils.TRACE("DetailLocationActivity", "loginFB : ");
            session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));

        } else {
            Session.openActiveSession(this, true, statusCallback);
        }
    }

    private void getUserData(Session session) {
        new com.facebook.Request(session, "/me", null, HttpMethod.GET,
                new com.facebook.Request.Callback() {

                    @Override
                    public void onCompleted(com.facebook.Response response) {
                        JSONObject jsonObject = null;
                        Utils.TRACE("DetailLocationActivity.getUserData(...).new Callback() {...}",
                                "onCompleted : " + response);
                        try {

                            jsonObject = new JSONObject(
                                    response.getGraphObject()
                                            .getInnerJSONObject()
                                            .toString());
                            Utils.TRACE("MainActivity.getUserData(...).new Callback() {...}",
                                    "onCompleted : " + jsonObject.toString());
                            Utils.setDataStringToSP(DetailLocationActivity.this, Utils.PREF_FB_ID,
                                    jsonObject.getString("id"));
                            Utils.setDataStringToSP(DetailLocationActivity.this,
                                    Utils.PREF_USERNAME,
                                    jsonObject.getString("name"));
                        } catch (JSONException e) {
                            Utils.TRACE("MenuUtamaActivity.getUserData(...).new Callback() {...}",
                                    "onCompleted : " + e.getMessage());
                        }
                    }
                }).executeAsync();
    }
}
